﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using UIWindows.Models.Interact;
using UIWindows.Models.ParameterModels;

namespace UIWindows.GlobalStatics
{
    [Attributes.Singleton]
    public class SystemConfigStatic
    {
        public SystemConfigModel SCM { get; set; }
        public InteractiveAddressModel IAddress { get; set; }
        public ObservableCollection<InteractAddressModel> IAddressList { get; set; }
        public ObservableCollection<PLCResectionModel> PLCResectionList { get; set; }

        public ObservableCollection<ScanSignalModel> SignalList { get; set; }
        public SystemConfigStatic()
        {
            if (!File.Exists(GlobalStatic.SystemConfigPath))
            {
                SCM = new SystemConfigModel();
                IAddress = new InteractiveAddressModel();
                IAddressList = new ObservableCollection<InteractAddressModel>();
                PLCResectionList = new ObservableCollection<PLCResectionModel>();
                SignalList = new ObservableCollection<ScanSignalModel>();
            }
            else
            {
                var model = JsonSerializer.Deserialize<Dictionary<string, object>>(File.ReadAllText(GlobalStatic.SystemConfigPath, Encoding.UTF8));
                SCM = JsonSerializer.Deserialize<SystemConfigModel>(model["SCM"].ToString());
                IAddress = JsonSerializer.Deserialize<InteractiveAddressModel>(model["IAddress"].ToString());
                IAddressList = JsonSerializer.Deserialize<ObservableCollection<InteractAddressModel>>(model["IAddressList"].ToString());
                PLCResectionList = JsonSerializer.Deserialize<ObservableCollection<PLCResectionModel>>(model["PLCResectionList"].ToString());
                SignalList = JsonSerializer.Deserialize<ObservableCollection<ScanSignalModel>>(model["SignalList"].ToString());
            }
        }

        public void Save() => File.WriteAllText(GlobalStatic.SystemConfigPath, JsonSerializer.Serialize(this, GlobalStatic.Options), Encoding.UTF8);
    }
}
